<?php

namespace App\Services;


use App\Models\User;
use App\Services\ThirdAPI\GameApiService;
use Illuminate\Support\Facades\Log;


class UserBalanceRecordService extends BaseService
{
    /**
     * 记录昨天余额
     */
    public static function insert()
    {
        $page = 0;
        $pageSize = 300;
        $yesterday = date('Y-m-d', strtotime('-1 days'));
        //检查今天是否已经有数据
        $result = DB::select($sql);

        if (!empty($result)) {
            Log::info('[user_balance_record] fail, yesterday balance data not null ');
            return;
        }

        while (true) {
            $query = User::find()
                ->select('u.id as user_id, u.name, u.wallet_id, f.balance, f.freeze_withdraw')
                ->from('user as u')
                ->leftJoin('funds as f', 'u.wallet_id=f.id')
                ->where(['f.status' => 'enabled'])
                ->orderBy('user_id')
                ->offset($pageSize * $page)
                ->limit($pageSize);
            $balance = $query->get()->toArray();
            if (empty($balance)) {
                break;
            }
            $page++;
            $record = [];
            foreach ($balance as $k => $b) {
                $record[$k]['user_id'] = $b['user_id'];
                $record[$k]['user_name'] = $b['name'];
                $record[$k]['date'] = $yesterday;
                $record[$k]['freeze_withdraw'] = $b['freeze_withdraw'] ?? 0;
                //计算总余额
                $total = $b['balance'] + $b['freeze_withdraw'];
                $walletId = $b['wallet_id'];
                //计算子钱包
                $sql = "SELECT SQL_CALC_FOUND_ROWS balance AS total, `name`, game_type FROM `funds_child` as f WHERE (f.pid = $walletId AND f.status = 'enabled')";
                $childCount = DB::select($sql);
                $sql = "SELECT id,`name` FROM `partner`";
                $gamesList = DB::select($sql);;
                $gamesList = is_array($gamesList) && !empty($gamesList)? array_column($gamesList, 'name', 'id') : [];
                //判断是否使用了共享钱包，使用了则不显示该子钱包
                foreach ($gamesList as $key => $val) {
                    $res = GameApiService::getTingGameConfig($val);
                    if (isset($res['useSharedwallet']) && $res['useSharedwallet'] == 'true') {
                        unset($gamesList[$key]);
                    }
                }

                foreach ($childCount as $child) {
                    if (in_array($child['game_type'], $gamesList)) {
                        $total += $child['total'];
                    }
                }

                $record[$k]['balance'] = $total;
            }

            DB::table('user_balance_record')->insert($record);
            Log::info('[user_balance_record] insert ok');
        }
    }
}
